import { Application, codo } from "egg";
import WeWorkBaseService from "./WeWorkBaseService";
import CodoError from "../CodoError";
import { WeWork } from "./type";

export default class Approval extends WeWorkBaseService {
	constructor(
		protected config: codo.WeWork.IWeWorkConfig,
		private accessToken: string,
		protected app: Application
	) {
		super(config, app);
	}

	/**
	 *获取一段时间内的审批单据号列表
	 * - 企微接口限制每次100，本封装方法已递归调用，直到全部获取到时间范围内的所有单据列表
	 * - 但调用时仍建议不能查询太宽时间范围，以免递归卡死或者超过企微接口调用次数频率（600/min）
	 * @param {Date} startTime
	 * @param {Date} endTime
	 * @return {*}
	 * @memberof PlatformQiyeWeixinShenPiService
	 */
	async getApprovalInfoNoList(startTime: Date, endTime: Date) {
		const result: string[] = [];
		const digui = async (cursor: string) => {
			const res = await this.getApprovalInfoNumList(startTime, endTime, cursor);
			result.push(...res.sp_no_list);
			if (res.new_next_cursor) {
				await digui(res.new_next_cursor);
			}
		};
		await digui("");
		return result;
	}

	/** 执行查询审批单据号列表 */
	async getApprovalInfoNumList(
		startTime: Date,
		endTime: Date,
		cursor: string = "",
		filters: { key: string; value: any }[] = []
	) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovalinfo?access_token=${this.accessToken}`;
		const starttime = Math.ceil(startTime.getTime() / 1000);
		const endtime = Math.floor(endTime.getTime() / 1000);
		const sendData = {
			starttime,
			endtime,
			cursor,
			size: 100,
			filters,
		};

		type Response = { sp_no_list: string[]; new_next_cursor?: string } & WeWork.IResponse;
		const res = await this.curl<Response>(url, {
			method: "POST",
			contentType: "json",
			dataType: "json",
			data: sendData,
		});
		if (res.data.errcode === 0) {
			return res.data;
		}
		this.app.logger.error("[企业微信 查询一段时间审批单据号列表] 错误 %s", res.data.errmsg);
		throw new CodoError(res.data.errmsg);
	}

	/**
	 *查询一个审批单号对应的审批单据详情
	 * - 接口频率限制 600次/分钟
	 * @param {string} sp_no 审批单号
	 * @return {*}
	 * @memberof PlatformQiyeWeixinShenPiService
	 */
	async getApprovalDetailInfo(sp_no: string) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovaldetail?access_token=${this.accessToken}`;
		type Response = { info: WeWork.IShenPiObject } & WeWork.IResponse;
		const res = await this.curl<Response>(url, {
			method: "POST",
			contentType: "json",
			dataType: "json",
			data: {
				sp_no,
			},
		});

		if (res.data.errcode === 0) {
			return res.data.info;
		}
		this.app.logger.error(
			"[企业微信 查询一个审批单据详情] 错误 %s %s",
			res.data.errcode,
			res.data.errmsg
		);
		throw new CodoError(res.data.errmsg);
	}

	/** 提交一个审批申请
	 * 申请单据的数据对象，由于表单是自定义的，需要先获取审批模板详情来获取到详细表单结构，然后自己填充数据。
	 * - https://developer.work.weixin.qq.com/document/path/91853
	 */
	async apply(data: WeWork.IApprovalApplyRequestObject) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/oa/applyevent?access_token=${this.accessToken}`;
		type Response = { sp_no: string } & WeWork.IResponse;
		const res = await this.curl<Response>(url, {
			method: "POST",
			contentType: "json",
			dataType: "json",
			data,
		});

		if (res.data.errcode === 0) {
			return res.data.sp_no;
		}
		this.app.logger.error(
			"[企业微信 提交一个审批申请] 错误 %s %s",
			res.data.errcode,
			res.data.errmsg
		);
		throw new CodoError(res.data.errmsg);
	}

	/** 获取审批模板详情
	 * - https://developer.work.weixin.qq.com/document/path/91982
	 */
	async getTemplateDetail(template_id: string) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/oa/gettemplatedetail?access_token=${this.accessToken}`;
		type Response = WeWork.IApprovalTemplateObject & WeWork.IResponse;
		const res = await this.curl<Response>(url, {
			method: "POST",
			contentType: "json",
			dataType: "json",
			data: {
				template_id,
			},
		});

		if (res.data.errcode === 0) {
			return res.data;
		}
		this.app.logger.error(
			"[企业微信 查询一个审批模板详情] 错误 %s %s",
			res.data.errcode,
			res.data.errmsg
		);
		throw new CodoError(res.data.errmsg);
	}
}
